import java.util.Arrays;

//建立大根堆
public class TestHeap{
    public int[] array;
    public int usedSize;//当前有效数组长度
    public TestHeap(){
        this.array = new int[10];
        this.usedSize = 0;
    }
    //初始化数组
    public void InitArray(int[] arrayClone){
        array = Arrays.copyOf(arrayClone, arrayClone.length);
        usedSize = array.length;
    }
    //创建大根堆
    public void createHeap(){
        for(int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--){
            adjustmentDown(parent, usedSize);
        }
    }
    //调整
    public void adjustmentDown(int parent, int len){
        //左子树结点下标
        int child = parent * 2 + 1;
        //调整
        while(child < len){
            //先判断有没有右孩子，如果右，找出最大值
            if(child + 1 < len && array[child] < array[child + 1]){
                child++;//如果右子树大，child++就指向他，如果左子树大，就不用管,直接进行下一步判断交换
            }
            //若左右子树的最大值大于父亲结点则交换
            if(array[child] > array[parent]){
                swap(array, child, parent);
                parent = child;
                child = parent * 2 + 1;
            } else{
                break;
            }
        }
    }
    //交换
    public void swap(int[] array, int child, int parent){
        int tmp = array[child];
        array[child] = array[parent];
        array[parent] = tmp;
    }
    //入队
    public void offer(int key){
        if(isFull()){
            array = Arrays.copyOf(array, array.length*2);
        }
        array[usedSize] = key;
        usedSize++;
        adjustmentUp(usedSize - 1);
    }
    //向上调整
    public void adjustmentUp(int child){
        int parent = (child - 1) / 2;
        while(parent >= 0){
            if(array[child] > array[parent]){
                swap(array, child, parent);
                child = parent;
                parent = (child - 1) / 2;
            }else{
                break;
            }
        }
    }
    //判断是否为满
    public boolean isFull(){
        return array.length == usedSize;
    }
    //出队
    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int ret = array[0];
        //将0与最后一个下标位置的值交换后删除(优先级队列出队元素一定是出最大值)
        swap(array,0,usedSize - 1);
        usedSize--;
        //向下调整
        adjustmentDown(0,usedSize);
        return ret;
    }
    //判断是否为空
    public boolean isEmpty(){
        return usedSize == 0;
    }
    //堆排序
    public void heapSort(){
        int end = usedSize - 1;
        while(end > 0){
            swap(array, end, 0);
            adjustmentDown(0, end);
            end--;
        }
    }
}
